package tag.in.activities;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import tag.in.Constants;
import tag.in.R;
import tag.in.TagAdapter;
import tag.in.TagInApplication;
import tag.in.data.Tag;
import tag.in.data.TagFetcher;
import tag.in.utils.HTTPRequests;

/**
 * 
 * Manage tags created by the user
 * 
 * @author andre
 */
public class TagManageActivity extends ListActivity {

    private static final String CLASSTAG = TagManageActivity.class.getSimpleName();
    private static final int MENU_GET_NEXT_PAGE = Menu.FIRST+1;
    private static final int MENU_GET_OPTIONS = Menu.FIRST;
    private static final int NUM_RESULTS_PER_PAGE = 8;
    
    private TextView empty;    
    private ProgressDialog progressDialog;
    private TagAdapter tagAdapter;
    private List<Tag> tags;
    private Button add_tag;
    private Button nearby_tag;
    private Button manage_tag;
    private Button list_tag;
    private EditText filter_name;
    private Button filter_name_button;
    
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            Log.v(Constants.LOGTAG, " " + TagManageActivity.CLASSTAG + " worker thread done, setup TagAdapter");
            progressDialog.dismiss();
            if ((tags == null) || (tags.size() == 0)) {
                empty.setText("Vazio");
            } else {
            	TagInApplication application = (TagInApplication) getApplication();
            	
                tagAdapter = new TagAdapter(TagManageActivity.this, tags, application.getTagCategories());
                setListAdapter(tagAdapter);
            }
        }
    };
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(Constants.LOGTAG, " " + TagManageActivity.CLASSTAG + " onCreate");

        // NOTE* This Activity MUST contain a ListView named "@android:id/list"
        // (or "list" in code) in order to be customized
        // http://code.google.com/android/reference/android/app/ListActivity.html
        this.setContentView(R.layout.tag_manage);
        
        /*
         * Main menu buttons
         */
        this.add_tag = (Button) findViewById(R.id.add_tag_button);
        this.nearby_tag = (Button) findViewById(R.id.nearby_tag_button);
        this.manage_tag = (Button) findViewById(R.id.manage_tag_button);
        this.list_tag = (Button) findViewById(R.id.list_tag_button);
        
        /*
         * Filter buttons
         */
        this.filter_name_button = (Button) findViewById(R.id.filter_name_tag_manage_button);
        this.filter_name = (EditText) findViewById(R.id.filter_name_tag_manage);
        this.empty = (TextView) findViewById(R.id.empty);

        // set list properties (for tags)
        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setEmptyView(this.empty);
        
        /*
         * Set Button Listeners
         * 
         */
        this.add_tag.setOnClickListener(new OnClickListener() {
        	@Override
            public void onClick(View v) {
        		handleAddTag();
            }
        });
        
        this.nearby_tag.setOnClickListener(new OnClickListener() {
        	@Override
            public void onClick(View v) {
        		handleNearbyTag();
            }
        });
        
        this.manage_tag.setOnClickListener(new OnClickListener() {
        	@Override
            public void onClick(View v) {
        		handleManageTag();
            }
        });
        
        this.list_tag.setOnClickListener(new OnClickListener() {
        	@Override
            public void onClick(View v) {
        		handleListTag();
            }
        });
        
        /*
         * Set Filter Buttons Listeners
         * 
         */
        this.filter_name_button.setOnClickListener(new OnClickListener() {
        	@Override
            public void onClick(View v) {
        		handleFilterNameTag();
            }
        });
    }   

    /*
     * Buttons Handler
     * Just send to its specific activity.
     * 
     */
    protected void handleAddTag() {
    	// call next Activity, VIEW_ADD
        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_ADD);
        startActivity(intent);
	}
    
    protected void handleNearbyTag() {
    	TagInApplication application = (TagInApplication) getApplication();
    	application.setTagAction("list");
    	application.setTagType("proximity");
    	
    	// call next Activity, VIEW_NEARBY
        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_NEARBY);
        startActivity(intent);
	}
    
    protected void handleManageTag() {
    	TagInApplication application = (TagInApplication) getApplication();
    	application.setTagAction("list");
    	application.setTagType("owned");
    	application.setTagOwner(application.getUsername());
    	
    	// call next Activity, VIEW_MANAGE
        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_MANAGE);
        startActivity(intent);
	}
    
    protected void handleListTag() {
    	TagInApplication application = (TagInApplication) getApplication();
    	application.setTagAction("list");
    	application.setTagType("all");
    	
    	// call next Activity, VIEW_LIST
        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_LIST);
        startActivity(intent);
	}
    
    protected void handleFilterNameTag() {
    	TagInApplication application = (TagInApplication) getApplication();
    	application.setTagAction("list");
    	application.setTagType("name");
    	application.setTagName(this.filter_name.getText().toString());
    	
    	// call next Activity, VIEW_LIST
        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_MANAGE);
        startActivity(intent);
	}
    
	@Override
    protected void onResume() {
        super.onResume();
        Log.v(Constants.LOGTAG, " " + TagManageActivity.CLASSTAG + " onResume");
        // get the current review criteria from the Application (global state placed there)
        TagInApplication application = (TagInApplication) getApplication();
        String tagAction = application.getTagAction();
        String tagType = application.getTagType();
        String tagOwner = application.getTagOwner();
        String tagName = application.getTagName();
        int tagCategory = application.getTagCategory();
        double tagLat = application.getTagLat();
        double tagLon = application.getTagLon();
        int tagRadious = application.getTagRadious();
        
        // get start from, an int, from extras
        int startFrom = getIntent().getIntExtra(Constants.STARTFROM_EXTRA, 0);
        
        loadTags(tagAction, tagType, tagOwner, tagCategory, tagName, TagManageActivity.NUM_RESULTS_PER_PAGE, startFrom, tagLat, tagLon, tagRadious);
    }    
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, TagManageActivity.MENU_GET_OPTIONS, 0, R.string.menu_get_options).setIcon(
                android.R.drawable.ic_menu_edit);
        menu.add(0, TagManageActivity.MENU_GET_NEXT_PAGE, 1, R.string.menu_get_next_page).setIcon(
            android.R.drawable.ic_menu_more);
        return true;
    }    

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        Intent intent = null;
        switch (item.getItemId()) {
            case MENU_GET_NEXT_PAGE:
                // increment the startFrom value and call this Activity again
                intent = new Intent(Constants.INTENT_ACTION_VIEW_MANAGE);
                intent.putExtra(Constants.STARTFROM_EXTRA, getIntent().getIntExtra(Constants.STARTFROM_EXTRA, 0)
                    + TagManageActivity.NUM_RESULTS_PER_PAGE);
                startActivity(intent);
                return true;
            case MENU_GET_OPTIONS:
            	intent = new Intent(Constants.INTENT_ACTION_VIEW_OPTIONS);
                startActivity(intent);
            	return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // set the current review to the Application (global state placed there)
        final TagInApplication application = (TagInApplication) getApplication();
        application.setCurrentTag(this.tags.get(position));
        
        //AlertDialog alert = 
        	new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.alert_manage_label)).setMessage(
                R.string.edit_tag_msg).setPositiveButton("Editar", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int arg1) {
                	// startFrom page is not stored in application, for example purposes it's a simple "extra"
                    Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_EDIT);
                    intent.putExtra(Constants.STARTFROM_EXTRA, getIntent().getIntExtra(Constants.STARTFROM_EXTRA, 0));
                    startActivity(intent);
                }
            }).setNegativeButton("Remover", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					HTTPRequests request = new HTTPRequests();
			        
			        List<NameValuePair> params = new ArrayList<NameValuePair>();
			        params.add(new BasicNameValuePair("action", "delete"));
			        params.add(new BasicNameValuePair("id", ""+application.getCurrentTag().id));
			        
			        int status = request.HTTPPost("http://"+application.getServerUrl()+":"+application.getServerPort()+"/"+Constants.SERVERAPP, params);
			        
			        /*
			         * Status:	200 - OK
			         * 			201 - CREATED
			         * 			403 - REQUEST FAILED
			         * 			500 - SERVER ERROR
			         * 			501 - BAD REQUEST
			         */
			        if(status==200) {
			        	// call next Activity, VIEW_LIST
				        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_MANAGE);
				        startActivity(intent);
			        }else if(status==403){
			        }else if(status==500){
			        }else if(status==501){
			        }else if(status==0){
			        }
				}
			}).setNeutralButton("Cancelar", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			}).show();
        
        /*alert.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface arg0) {
				// TODO Auto-generated method stub
				// startFrom page is not stored in application, for example purposes it's a simple "extra"
		        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_MANAGE);
		        //intent.putExtra(Constants.STARTFROM_EXTRA, getIntent().getIntExtra(Constants.STARTFROM_EXTRA, 1));
		        startActivity(intent);
			}
        });*/
        /*
        new AlertDialog.Builder(this).setTitle("Tag").setMessage(
                application.getCurrentTag().toString()).setPositiveButton("Continue", new android.content.DialogInterface.OnClickListener() {

                public void onClick(final DialogInterface dialog, final int arg1) {
                }
            }).show();
        */
        
        // startFrom page is not stored in application, for example purposes it's a simple "extra"
        //Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_MANAGE);
        //intent.putExtra(Constants.STARTFROM_EXTRA, getIntent().getIntExtra(Constants.STARTFROM_EXTRA, 1));
        //startActivity(intent);
    }    
    
    private void loadTags(String action, String type, String owner, int category, String name, int n, int offset, double lat, double lon, int radious) {
    	TagInApplication application = (TagInApplication) getApplication();
    	
        Log.v(Constants.LOGTAG, " " + TagManageActivity.CLASSTAG + " load tags");

        final TagFetcher rf = new TagFetcher("http://"+application.getServerUrl()+":"+application.getServerPort()+"/"+Constants.SERVERAPP+"?",action, type, owner, category, name, n, offset, lat, lon, radious);

        this.progressDialog = ProgressDialog.show(this, " A processar...", " A obter Tags", true, false);

        // get reviews in a separate thread for ProgressDialog/Handler
        // when complete send "empty" message to handler
        new Thread() {
            @Override
            public void run() {
                tags = rf.getTags();
                handler.sendEmptyMessage(0);
            }
        }.start();
    }
}
